package br.com.viewcar.util;

import java.io.IOException;
import java.util.List;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import br.com.viewcar.web.bean.BaseBean;

public class DownloadFileUtil extends BaseBean {

	private static final Log logger = LogFactory.getLog(DownloadFileUtil.class);

	public static final int TYPE_PDF = 1;
	public static int TYPE_RTF = 2;


	public static synchronized String downloadKMLFile(byte[] content) {

		try {
			return downloadFile(ZipUtil.zip("Checkrota.kml", content), "Checkrota.kmz", "application/vnd.google-earth.kmz");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return FAIL;
		}
	}

	public static synchronized String downloadKMLNoZipFile(byte[] content) {

		try {
			return downloadFile(content, "Checkrota.kmz", "application/vnd.google-earth.kmz");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return FAIL;
		}
	}

	public static synchronized String downloadFile(byte[] content, String fileName, String mimeType) {

		FacesContext facesContext = FacesContext.getCurrentInstance();
		ExternalContext context = facesContext.getExternalContext();
		HttpServletResponse response = (HttpServletResponse) context.getResponse();
		response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
		response.setHeader("Content-Transfer-Encoding", "binary");
		response.setContentType(mimeType);
		response.setContentLength(content.length);

		try {
			ServletOutputStream out = response.getOutputStream();
			out.write(content, 0, content.length);
			out.flush();
			facesContext.responseComplete();
			return SUCCESS;

		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			return FAIL;
		}
	}

	public static String showPointsGoogleEarthFile(List entities, String resourceName, boolean viewPoints) throws Exception {

		String label = viewPoints == true ? "pontosCliente" : "rotaCliente";
		if (entities != null && entities.size() > 0) {
			List rotaCliente = entities;
			byte[] bytes = VelocityUtil.merge(resourceName, new String[]{label, "viewPoints"}, new Object[]{rotaCliente, viewPoints });
			return downloadKMLNoZipFile(bytes);
		}

		return SUCCESS;
	}
}